import {isEmpty} from "../util/utils";
import store from "./index";
export const local = {
    set(key: string, value: any) {
        localStorage.setItem(key, JSON.stringify(value));
    },
    setString(key: string, value: string) {
        localStorage.setItem(key, value);
    },
    get<T = any>(key: string): T {
        const value = localStorage.getItem(key);
        if (value && !isEmpty(value)) {
            return <T>JSON.parse(value);
        }
        return null as any;
    },
    getString(key: string): string {
        const value = localStorage.getItem(key);
        return value === null ? "" : value;
    },
    clear() {
        localStorage.clear();
    },
    remove(key: string) {
        localStorage.removeItem(key);
    }
};

export const session = {
    set(key: string, value: any) {
        sessionStorage.setItem(key, JSON.stringify(value));
    },
    setString(key: string, value: string) {
        sessionStorage.setItem(key, value);
    },
    get<T = any>(key: string): T {
        const value = sessionStorage.getItem(key);
        if (value && !isEmpty(value)) {
            return <T>JSON.parse(value);
        }
        return null as any;
    },
    getString(key: string): string {
        const value = sessionStorage.getItem(key);
        return value === null ? "" : value;
    },
    clear() {
        sessionStorage.clear();
    },
    remove(key: string) {
        sessionStorage.removeItem(key);
    }
};

export const initStorage = function () {
    if (!sessionStorage.length) {
        local.setString("getSessionStorageData", Date.now().toString());
    }
    window.addEventListener("storage", function (event) {
        const val = event.newValue;
        if (!val) {
            return;
        }
        if (event.key === "getSessionStorageData") {
            local.set("storeSessionData", window.sessionStorage);
            local.remove("storeSessionData");
        }
        if (event.key === "storeSessionData" && !sessionStorage.length) {
            const data = JSON.parse(val);
            for (let key in data) {
                session.setString(key, data[key]);
            }
        }
    });
    const appStore = store();
    appStore.syncDarkLabel();
    appStore.syncPublicKey();
    appStore.syncEnumOptionList();
}
